package com.kgc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.mapper.ProductMapper;
import com.kgc.mapper.SaleMapper;
import com.kgc.mapper.UserMapper;
import com.kgc.pojo.Product;
import com.kgc.pojo.Sale;
import com.kgc.pojo.SaleExample;
import com.kgc.pojo.User;
import com.kgc.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SaleServiceImpl implements SaleService {
    @Autowired
    private SaleMapper saleMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public Integer addSale(Sale sale,Product product) throws RuntimeException {
        Integer saleRow=saleMapper.insertSelective(sale);
        Integer productRow=productMapper.updateByPrimaryKeySelective(product);
        if(saleRow+productRow<2){
            throw new RuntimeException();
        }
        return saleRow+productRow;
    }

    @Override
    public PageInfo<Sale> selectSaleList(String order,Integer pageNo,Integer pageSize) {
        SaleExample saleExample=new SaleExample();
        saleExample.setOrderByClause(order);

        PageHelper.startPage(pageNo,pageSize);

        List<Sale> sales=saleMapper.selectByExample(saleExample);
        for (Sale sale : sales) {
            Product product=productMapper.selectByPrimaryKey(sale.getProductId());
            User user=userMapper.selectByPrimaryKey(sale.getUserId());
            sale.setProduct(product);
            sale.setUser(user);
        }

        PageInfo<Sale> pageInfo=new PageInfo<Sale>(sales);

        return pageInfo;
    }
}
